package com.lw.lost.fragments

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.lw.lost.R
import com.lw.lost.databinding.FragmentPublishBinding
import com.lw.lost.db.DBlost
import com.lw.lost.utils.FileUtils
import com.lw.lost.utils.PreferenceUtils

class PublishFragment : Fragment() {

    private var _binding: FragmentPublishBinding? = null
    private val binding get() = _binding!!
    private lateinit var db: DBlost
    private var selectedImageUri: Uri? = null

    private val getContent = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.data?.let { uri ->
                selectedImageUri = uri
                showImagePreview(uri)
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentPublishBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        db = DBlost(requireContext())

        setupImagePicker()
        setupPublishButton()
        setupRemoveButton()
    }

    private fun setupImagePicker() {
        binding.btnAddImage.setOnClickListener {
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            getContent.launch(intent)
        }
    }

    private fun setupPublishButton() {
        binding.btnPublish.setOnClickListener {
            val content = binding.etContent.text.toString().trim()
            if (content.isEmpty()) {
                Toast.makeText(context, "请输入内容", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            publishPost(content)
        }
    }

    private fun setupRemoveButton() {
        binding.btnRemoveImage.setOnClickListener {
            selectedImageUri = null
            binding.cardPreview.visibility = View.GONE
            binding.btnRemoveImage.visibility = View.GONE
        }
    }

    private fun showImagePreview(uri: Uri) {
        binding.cardPreview.visibility = View.VISIBLE
        binding.btnRemoveImage.visibility = View.VISIBLE
        Glide.with(this)
            .load(uri)
            .into(binding.ivPreview)
    }

    private fun publishPost(content: String) {
        val userId = PreferenceUtils.getUserId(requireContext())
        var imageUrl: String? = null

        // 如果选择了图片，保存到应用私有存储
        selectedImageUri?.let { uri ->
            FileUtils.saveImageToPrivateStorage(requireContext(), uri)?.let { file ->
                imageUrl = file.absolutePath
            }
        }

        // 发布动态
        val postId = db.postDao.insert(userId, content, imageUrl)
        
        if (postId > 0) {
            // 发送通知给所有好友
            val cursor = db.userDao.getFriends(userId)
            cursor.use { 
                while(it.moveToNext()) {
                    val friendId = it.getLong(it.getColumnIndexOrThrow("userId"))
                    // 插入一条通知消息
                    db.messageDao.insert(
                        senderId = userId,
                        receiverId = friendId,
                        content = "发布了新动态：$content",
                        imageUrl = imageUrl
                    )
                }
            }
            
            Toast.makeText(context, "发布成功", Toast.LENGTH_SHORT).show()
            clearInputs()
        } else {
            Toast.makeText(context, "发布失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun clearInputs() {
        binding.etContent.text?.clear()
        selectedImageUri = null
        binding.ivPreview.setImageDrawable(null)
        binding.cardPreview.visibility = View.GONE
        binding.btnRemoveImage.visibility = View.GONE
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 